package com.kmdd.xtds.ui

import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import com.kmdd.xtds.configs.PrefsManager
import com.kmdd.xtds.databinding.ActivityBloodOxygenBinding
import com.kmdd.xtds.room.BloodPressure
import com.kmdd.xtds.room.BloodPressureDatabase
import com.kmdd.xtds.util.LiveDataBus
import com.kmdd.xtds.util.TimeUtil
import com.kmdd.xtds.util.launch
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class BloodOxygenAddActivity : AppCompatActivity() {
    private lateinit var binding: ActivityBloodOxygenBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBloodOxygenBinding.inflate(layoutInflater)
        setContentView(binding.root)
        immersionBar {
            transparentBar()
            keyboardEnable(true)
            fitsSystemWindows(false)
            statusBarDarkFont(false)
        }
        initView()
    }

    private fun initView() {
        binding.tvConfirm.setOnClickListener {
            confirm()
        }

        binding.ivBack.setOnClickListener {
            finish()
        }
    }

    private fun confirm() {
        if (TextUtils.isEmpty(binding.edit1.text)) {
            Toast.makeText(this, "收缩压（高压）不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(binding.edit2.text)) {
            Toast.makeText(this, "舒张压（低压）不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(binding.edit3.text)) {
            Toast.makeText(this, "血氧饱和度不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        val bloodPressure = BloodPressure(
            binding.edit1.text.toString(),
            binding.edit2.text.toString(),
            binding.edit3.text.toString(),
            TimeUtil.getTime(System.currentTimeMillis(), TimeUtil.DATEFORMATER2),
            TimeUtil.getTime(System.currentTimeMillis(), TimeUtil.DATEFORMATER6)
        )
        launch {
            withContext(Dispatchers.IO) {
                BloodPressureDatabase.getInstance(this@BloodOxygenAddActivity)
                    ?.bloodPressureDao()
                    ?.insert(bloodPressure)
            }
            PrefsManager.saveShrink(binding.edit1.text.toString())
            PrefsManager.saveDiastolicBloodPressure(binding.edit2.text.toString())
            PrefsManager.saveBloodOxygenSaturation(binding.edit3.text.toString())
            LiveDataBus.get().with("refreshBloodOxygenData").postValue("1")
            Toast.makeText(this@BloodOxygenAddActivity, "保存成功", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
}